<template>
  <div class="archive-receive-digitize-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>档案接收与数字化</span>
      </div>
      <el-form :model="archiveForm" ref="archiveForm" label-width="120px">
        <el-form-item label="档案标题" prop="title" :rules="[{ required: true, message: '请输入档案标题', trigger: 'blur' }]">
          <el-input v-model="archiveForm.title"></el-input>
        </el-form-item>
        
        <!-- 电子档案上传 -->
        <el-form-item label="电子档案上传">
          <el-upload
            class="upload-demo"
            ref="upload"
            action="#"
            :auto-upload="false"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            :file-list="fileList"
            :limit="1"
            accept=".doc,.docx,.pdf,.xls,.xlsx,.ppt,.pptx,.txt,.jpg,.jpeg,.png,.gif"
          >
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">支持文档、图片、视频等格式，单次上传文件大小不超过50MB</div>
          </el-upload>
        </el-form-item>

        <!-- 文档内容识别区域 -->
        <el-form-item label="文档内容识别">
          <div class="ocr-section">
            <div class="ocr-upload-area">
              <h4>上传图片进行文档内容识别</h4>
              <el-upload
                class="ocr-uploader"
                drag
                action="#"
                :auto-upload="false"
                :on-change="handleOcrImageChange"
                :on-remove="handleOcrImageRemove"
                :file-list="ocrFileList"
                :limit="1"
                accept=".jpg,.jpeg,.png,.gif,.bmp"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将图片拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">支持JPG、PNG、GIF、BMP格式，文件大小不超过4MB</div>
              </el-upload>
              <div class="ocr-buttons" v-if="ocrFileList.length > 0">
                <el-button type="primary" @click="performOcr" :loading="ocrLoading">
                  <i class="el-icon-view"></i>
                  识别文档内容
                </el-button>
                <el-button @click="clearOcrImage">
                  <i class="el-icon-delete"></i>
                  清除图片
                </el-button>
              </div>
            </div>
            
            <div class="ocr-result-area" v-if="ocrResult || archiveForm.ocrContent">
              <h4>文档内容识别结果</h4>
              <el-input
                type="textarea"
                :rows="8"
                v-model="archiveForm.ocrContent"
                placeholder="这里将显示识别出的文档内容，您可以编辑修改">
              </el-input>
              <div class="ocr-actions" v-if="ocrResult">
                <el-button size="small" @click="replaceOcrContent">替换内容</el-button>
                <el-button size="small" @click="appendOcrContent">追加内容</el-button>
                <el-button size="small" type="danger" @click="clearOcrResult">清空结果</el-button>
              </div>
            </div>
            
            <div class="ocr-status" v-if="ocrLoading">
              <i class="el-icon-loading"></i>
              <span>正在识别文档内容，请稍候...</span>
            </div>
          </div>
        </el-form-item>

        <!-- 提示信息 -->
        <el-form-item>
          <el-alert
            title="请注意：电子档案文件和文档内容至少需要提供一个"
            type="warning"
            :closable="false"
            show-icon>
          </el-alert>
        </el-form-item>

        <el-form-item label="纸质档案地点" prop="physicalLocation">
          <el-input v-model="archiveForm.physicalLocation" placeholder="请输入纸质档案存储地点"></el-input>
        </el-form-item>
        <el-form-item label="档案类型" prop="archiveType">
          <el-select v-model="archiveForm.archiveType" placeholder="请选择档案类型">
            <el-option label="公共档案" value="公共档案"></el-option>
            <el-option label="个人档案" value="个人档案"></el-option>
            <el-option label="受限档案" value="受限档案"></el-option>
            <el-option label="企业公告" value="企业公告"></el-option>
            <el-option label="培训资料" value="培训资料"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="保密等级" prop="securityLevel" :rules="[{ required: true, message: '请选择保密等级', trigger: 'change' }]">
          <el-select v-model="archiveForm.securityLevel" placeholder="请选择保密等级">
            <el-option label="绝密" value="绝密"></el-option>
            <el-option label="机密" value="机密"></el-option>
            <el-option label="秘密" value="秘密"></el-option>
            <el-option label="内部" value="内部"></el-option>
            <el-option label="公开" value="公开"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可见范围" prop="visibleScope">
          <el-input v-model="archiveForm.visibleScope" placeholder="默认为all, 可指定部门或用户ID"></el-input>
        </el-form-item>
        <el-form-item label="自动分类" prop="autoCategory">
          <el-input v-model="archiveForm.autoCategory" placeholder="系统自动分类"></el-input>
        </el-form-item>
        <el-form-item label="自动标签" prop="autoTags">
          <el-input v-model="archiveForm.autoTags" placeholder="系统自动生成标签, 多个用逗号分隔"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('archiveForm')">立即创建</el-button>
          <el-button @click="resetForm('archiveForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import service from '@/utils/request';

export default {
  name: 'ArchiveReceiveDigitize',
  data() {
    return {
      archiveForm: {
        title: '',
        physicalLocation: '',
        archiveType: '',
        securityLevel: '',
        visibleScope: 'all',
        autoCategory: '',
        autoTags: '',
        uploadedFile: null,
        ocrContent: '' // OCR识别内容
      },
      fileList: [],
      ocrFileList: [], // 添加OCR文件列表
      ocrResult: '', // 添加OCR识别结果
      ocrUploadUrl: '/ocr/recognize', // 修改OCR请求URL，去掉/company前缀
      ocrLoading: false
    };
  },
  methods: {
    handleFileChange(file, fileList) {
      this.archiveForm.uploadedFile = file.raw;
      this.fileList = [file];
    },
    handleFileRemove(file, fileList) {
      this.archiveForm.uploadedFile = null;
      this.fileList = [];
    },
    
    // 添加缺失的OCR图片处理方法
    handleOcrImageChange(file, fileList) {
      this.ocrFileList = [file];
    },
    
    handleOcrImageRemove(file, fileList) {
      this.ocrFileList = [];
      this.ocrResult = '';
    },
    
    // 执行OCR识别
    performOcr() {
      if (this.ocrFileList.length === 0) {
        this.$message.error('请先上传图片');
        return;
      }
      
      this.ocrLoading = true;
      const formData = new FormData();
      formData.append('file', this.ocrFileList[0].raw);
      
      const token = localStorage.getItem('token');
      const headers = {};
      if (token) {
        headers['token'] = token;
      }
      
      service.post(this.ocrUploadUrl, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          ...headers
        }
      })
      .then(res => {
        this.ocrLoading = false;
        if (res.data.code === 200) {
          this.ocrResult = res.data.data || '';
          if (this.ocrResult) {
            this.$message.success('OCR识别成功！');
          } else {
            this.$message.warning('未识别到文字内容');
          }
        } else {
          this.$message.error(res.data.message || 'OCR识别失败');
        }
      })
      .catch(error => {
        this.ocrLoading = false;
        console.error('OCR识别错误:', error);
        this.$message.error('OCR识别失败，请检查网络连接');
      });
    },
    
    // 清除OCR图片
    clearOcrImage() {
      this.ocrFileList = [];
      this.ocrResult = '';
    },
    
    // 替换OCR内容
    replaceOcrContent() {
      this.archiveForm.ocrContent = this.ocrResult;
      this.$message.success('内容已替换');
    },
    
    // 追加OCR内容
    appendOcrContent() {
      if (this.archiveForm.ocrContent) {
        this.archiveForm.ocrContent += '\n' + this.ocrResult;
      } else {
        this.archiveForm.ocrContent = this.ocrResult;
      }
      this.$message.success('内容已追加');
    },
    
    // 清空OCR结果
    clearOcrResult() {
      this.archiveForm.ocrContent = ''; // 只清空表单中的OCR内容，保留结果区域显示
      this.$message.success('内容已清空');
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 验证：文件和OCR内容至少需要一个
          const hasFile = this.archiveForm.uploadedFile != null;
          const hasOcrContent = this.archiveForm.ocrContent && this.archiveForm.ocrContent.trim() !== '';
          
          if (!hasFile && !hasOcrContent) {
            this.$message.error('请上传电子档案文件或提供OCR识别内容，两者至少选择一个');
            return false;
          }

          const formData = new FormData();
          
          // 只有在有文件时才添加文件参数
          if (hasFile) {
            formData.append('file', this.archiveForm.uploadedFile);
          }
          
          formData.append('title', this.archiveForm.title);
          formData.append('physicalLocation', this.archiveForm.physicalLocation);
          formData.append('archiveType', this.archiveForm.archiveType);
          formData.append('securityLevel', this.archiveForm.securityLevel);
          formData.append('visibleScope', this.archiveForm.visibleScope);
          
          // 添加OCR内容
          if (hasOcrContent) {
            formData.append('ocrContent', this.archiveForm.ocrContent.trim());
          }

          const token = localStorage.getItem('token');
          const headers = {};
          if (token) {
            headers['token'] = token;
          }

          service.post('/archive/upload', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              ...headers
            }
          })
            .then(res => {
              if (res.data.code === 200) {
                this.$message.success(res.data.message || '档案上传成功');
                
                // 先保存服务器返回的自动分类和标签数据
                let autoCategory = '';
                let autoTags = '';
                if (res.data.data) {
                  autoCategory = res.data.data.autoCategory || '';
                  autoTags = res.data.data.autoTags || '';
                }
                
                // 重置表单
                this.resetForm(formName);
                
                // 在重置表单后，设置自动分类和标签（供用户查看）
                this.archiveForm.autoCategory = autoCategory;
                this.archiveForm.autoTags = autoTags;
              } else {
                this.$message.error(res.data.message || '档案上传失败');
              }
            })
            .catch(error => {
              console.error("Error uploading archive:", error);
              this.$message.error('档案上传失败');
            });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.archiveForm.visibleScope = 'all';
      this.archiveForm.autoCategory = '';
      this.archiveForm.autoTags = '';
      this.archiveForm.uploadedFile = null;
      this.archiveForm.ocrContent = '';
      this.$refs.upload.clearFiles();
      this.fileList = [];
      // 重置OCR相关数据
      this.ocrFileList = [];
      this.ocrResult = '';
      this.ocrLoading = false;
    }
  }
}
</script>

<style scoped>
.archive-receive-digitize-container {
  padding: 20px;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both
}
.box-card {
  width: 100%;
}
.el-upload__tip {
  font-size: 12px;
  color: #909399;
}

/* OCR相关样式 */
.ocr-section {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  padding: 15px;
  background-color: #fafafa;
}

.ocr-upload-section {
  margin-bottom: 15px;
}

.ocr-upload {
  width: 100%;
}

.ocr-loading {
  margin: 15px 0;
}

.ocr-result-section {
  margin-top: 15px;
}

.ocr-actions {
  margin-top: 10px;
  text-align: right;
}

.ocr-actions .el-button {
  margin-left: 10px;
}
</style> 